package com.shr25.v2.controller;

import cn.hutool.core.collection.CollUtil;
import com.shr25.v2.common.base.BaseController;
import com.shr25.v2.common.conf.redis.RedisService;
import com.shr25.v2.model.admin.TSysUser;
import com.shr25.v2.qq.QQUserInfo;
import com.shr25.v2.qq.QQUtils;
import com.shr25.v2.qq.config.QQConfig;
import com.shr25.v2.service.admin.ITSysUserService;
import com.shr25.v2.shiro.token.MyAuthenticationToken;
import com.shr25.v2.shiro.util.ShiroUtils;
import com.shr25.v2.util.ServletUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 如果有前台这儿写前台访问方法
 * @ClassName: IndexController
 * @author fuce
 * @date 2019-10-21 00:15
 */
@Slf4j
@Api(tags = "首页模块")
@Controller
public class IndexController extends BaseController{

	@Autowired
	private QQConfig qqConfig;

	@Autowired
	private RedisService redisService;

	@Autowired
	private ITSysUserService sysUserService;
	
	/**
	 * 前台访问 域名:端口 例如:localhost:80的get请求
	 * @param map
	 * @return
	 * @author huobing
	 * @Date 2022年03月12日 下午13:01:56
	 */
	@ApiOperation(value="前台",notes="前台")
	@GetMapping("/")
	public String index(ModelMap map) {
			//直接访问后台用
		return "index";
	}
	/**
	 * 图标
	 */
	@ApiOperation(value="前台",notes="前台")
	@GetMapping("/favicon.ico")
	public void favicon(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取容器资源解析器
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			//获取所有匹配的文件
			Resource resource = resolver.getResource("/static/favicon.ico");
			InputStream inputStream = resource.getInputStream();
			//设置发送到客户端的响应内容类型
			response.setContentType("image/*");
			//读取本地图片输入流
			int i = inputStream.available();
			//byte数组用于存放图片字节数据
			byte[] buff = new byte[i];
			inputStream.read(buff);
			response.getOutputStream().write(buff);
			inputStream.close();
		} catch (IOException e) {
			if (log.isWarnEnabled()) {
				log.warn("读取文件流失败，写入本地库失败！ " + e);
			}
		}
	}

	/**
	 * 前台访问/index的get请求
	 * @param map
	 * @return
	 * @author huobing
	 * @Date 2022年03月12日 下午13:01:56
	 */
	@ApiOperation(value="前台",notes="前台")
	@GetMapping("/{path}")
	public String index2(ModelMap map, @PathVariable String path) {
		//直接访问后台用
		//return "redirect:/admin/login"
		return path;
	}

	/**
	 * 请求到登陆界面
	 *
	 * @param modelMap
	 * @return
	 */
	@ApiOperation(value = "qq登录", notes = "请求到登陆界面")
	@GetMapping("/loginbyqq")
	public String loginbyqq(ModelMap modelMap) {
		String referer =  ServletUtils.getReferer();
		if(referer == null){
			referer = redisService.getCacheObject(ShiroUtils.getSessionId());
		}
		log.info("referer:{}", referer);
		String state = UUID.randomUUID().toString();
		redisService.setCacheObject(state, referer, 60L, TimeUnit.SECONDS);
		return "redirect:https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="+qqConfig.getAppid()+"&state="+state+"&redirect_uri="+qqConfig.getRedirectUri();
	}

	/**
	 * 请求到登陆界面
	 *
	 * @param modelMap
	 * @return
	 */
	@ApiOperation(value = "qq登录", notes = "请求到登陆界面")
	@GetMapping(value = "/callback/qq")
	public String qqLogin(String code, String  state,ModelMap modelMap) {
		String referer = redisService.getCacheObject(state);
		log.info("referer:{}", referer);
		QQUserInfo qqUserInfo = QQUtils.getUserInfo(qqConfig, code);
		if(qqUserInfo != null && qqUserInfo.getOpenid() != null){
			try{
				ServletUtils.getSession().setAttribute("qqUserInfo", qqUserInfo);
				TSysUser user = ShiroUtils.getUser();
				if(user == null){
					TSysUser userInfo = new TSysUser();
					userInfo.setQqOpenid(qqUserInfo.getOpenid());
					List<TSysUser> list = sysUserService.selectTSysUserList(userInfo);

					if (CollUtil.isNotEmpty(list)) {
						userInfo = list.get(0);
						SecurityUtils.getSubject().login(new MyAuthenticationToken(userInfo, "qq"));
					}
				}else if(user.getQqOpenid() == null){
					user.setQqOpenid(qqUserInfo.getOpenid());
					user.setQqName(qqUserInfo.getNickname());
					user.setQqFigureurl(qqUserInfo.getFigureurl_qq());
					user.setAvatar(qqUserInfo.getFigureurl_qq());
					ShiroUtils.setUser(user);
					TSysUser newUser = new TSysUser();
					newUser.setId(user.getId());
					newUser.setQqOpenid(qqUserInfo.getOpenid());
					newUser.setQqName(qqUserInfo.getNickname());
					newUser.setQqFigureurl(qqUserInfo.getFigureurl_qq());
					newUser.setAvatar(qqUserInfo.getFigureurl_qq());
					sysUserService.updateTSysUser(newUser);
				}
			}catch (Exception e){
				log.error(e.getMessage(), e);
			}
		}
		return "redirect:"+referer;
	}
}
